package com.fqy.ticket.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fqy.ticket.business.domain.*;
import com.fqy.ticket.business.enums.SeatTypeEnum;
import com.fqy.ticket.business.enums.TrainTypeEnum;
import com.fqy.ticket.business.mapper.DailyTrainSeatMapper;
import com.fqy.ticket.business.mapper.DailyTrainTicketMapper;
import com.fqy.ticket.business.req.DailyTrainTicketQueryReq;
import com.fqy.ticket.business.req.DailyTrainTicketSaveReq;
import com.fqy.ticket.business.resp.DailyTrainTicketQueryResp;
import com.fqy.ticket.common.resp.PageResp;
import com.fqy.ticket.common.util.SnowUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class DailyTrainTicketService {

    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainTicketService.class);

    @Resource
    private DailyTrainTicketMapper dailyTrainTicketMapper;

    @Resource
    private DailyTrainSeatMapper dailyTrainSeatMapper;

    @Resource
    private DailyTrainStationService dailyTrainStationService;

    /**
     * 保存DailyTrainTicket记录（新增或更新）
     * @param req 保存请求对象
     */
    public void save(DailyTrainTicketSaveReq req) {
        DateTime now = DateTime.now();
        DailyTrainTicket dailyTrainTicket = BeanUtil.copyProperties(req, DailyTrainTicket.class);

        if (ObjectUtil.isNull(dailyTrainTicket.getId())) {
            // 新增逻辑
            dailyTrainTicket.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainTicket.setCreateTime(now);
            dailyTrainTicket.setUpdateTime(now);
            dailyTrainTicketMapper.insert(dailyTrainTicket);
            LOG.info("新增DailyTrainTicket成功，ID：{}", dailyTrainTicket.getId());
        } else {
            // 更新逻辑
            dailyTrainTicket.setUpdateTime(now);
            dailyTrainTicketMapper.updateByPrimaryKey(dailyTrainTicket);
        }
    }
    @Cacheable(value = "DailyTrainTicketService.queryList3")
    public PageResp<DailyTrainTicketQueryResp> queryList3(DailyTrainTicketQueryReq req) {
        LOG.info("测试缓存击穿");
        return null;
    }
    /**
     * 分页查询DailyTrainTicket列表
     * @param req 查询请求对象（包含分页信息）
     * @return 分页结果
     */
    // @Cacheable(value = "DailyTrainTicketService.queryList")
    // @CachePut(value = "DailyTrainTicketService.queryList")
    public PageResp<DailyTrainTicketQueryResp> queryList(DailyTrainTicketQueryReq req) {
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        dailyTrainTicketExample.setOrderByClause("id desc");
        DailyTrainTicketExample.Criteria criteria = dailyTrainTicketExample.createCriteria();

        if (ObjUtil.isNotNull(req.getDate())) {
            criteria.andDateEqualTo(req.getDate());
        }
        if (ObjUtil.isNotEmpty(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }
        if (ObjUtil.isNotEmpty(req.getStart())) {
            criteria.andStartEqualTo(req.getStart());
        }
        if (ObjUtil.isNotEmpty(req.getEnd())) {
            criteria.andEndEqualTo(req.getEnd());
        }

        LOG.info("查询DailyTrainTicket列表，页码：{}，每页条数：{}", req.getPage(), req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<DailyTrainTicket> dailyTrainTicketList = dailyTrainTicketMapper.selectByExample(dailyTrainTicketExample);

        PageInfo<DailyTrainTicket> pageInfo = new PageInfo<>(dailyTrainTicketList);
        LOG.info("查询结果：总行数={}，总页数={}", pageInfo.getTotal(), pageInfo.getPages());

        List<DailyTrainTicketQueryResp> list = BeanUtil.copyToList(dailyTrainTicketList, DailyTrainTicketQueryResp.class);

        PageResp<DailyTrainTicketQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 根据ID删除DailyTrainTicket记录
     * @param id 记录ID
     */
    public void delete(Long id) {
        int count = dailyTrainTicketMapper.deleteByPrimaryKey(id);
    }
    @Transactional
    public void genDaily(DailyTrain dailyTrain, Date date, String trainCode) {
        LOG.info("开始生成日期[{}], 车次[{}]的座位信息",  DateUtil.formatDate(date), trainCode);
        // 删除某日某车次的余票信息
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        dailyTrainTicketExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode);
        dailyTrainTicketMapper.deleteByExample(dailyTrainTicketExample);

        // 查询当前车次的车站信息
        List<TrainStation> stations = dailyTrainStationService.selectByTrainCode(trainCode);
        if (CollUtil.isEmpty(stations)) {
            LOG.info("该车次没有车站基础数据，生成该车站的余票信息结束");
            return;
        }

        DateTime now = DateTime.now();

        for (int i=0; i<stations.size(); i++) {
            TrainStation startStation = stations.get(i);
            BigDecimal sumKM = new BigDecimal(0);
            for (int j=i+1; j<stations.size(); j++) {
                TrainStation endStation = stations.get(j);
                sumKM = sumKM.add(endStation.getKm());

                DailyTrainTicket ticket = new DailyTrainTicket();
                ticket.setId(SnowUtil.getSnowflakeNextId());
                ticket.setDate(date);
                ticket.setTrainCode(trainCode);
                ticket.setStart(startStation.getName());
                ticket.setStartPinyin(startStation.getNamePinyin());
                // 出发时间应该是出战时间
                ticket.setStartTime(startStation.getOutTime());
                ticket.setStartIndex(startStation.getIndex());
                ticket.setEnd(endStation.getName());
                ticket.setEndPinyin(endStation.getNamePinyin());
                // 到达时间应该是入站时间
                ticket.setEndTime(endStation.getInTime());
                ticket.setEndIndex(endStation.getIndex());

                // 票价 = 里程之和 * 座位单价 * 车次类型系数
                String trainType = dailyTrain.getType();
                // 计算票价系数：TrainTypeEnum.priceRate
                // 一趟车就一种类型，所以rate就一个，但是有多种座位
                BigDecimal priceRate = EnumUtil.getFieldBy(TrainTypeEnum::getPriceRate, TrainTypeEnum::getCode, trainType);
                BigDecimal ydzPrice = sumKM.multiply(SeatTypeEnum.YDZ.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal edzPrice = sumKM.multiply(SeatTypeEnum.EDZ.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal rwPrice = sumKM.multiply(SeatTypeEnum.RW.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal ywPrice = sumKM.multiply(SeatTypeEnum.YW.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);

                ticket.setYdz(countSeat(date, trainCode, SeatTypeEnum.YDZ.getCode()));
                ticket.setYdzPrice(ydzPrice);
                ticket.setEdz(countSeat(date, trainCode, SeatTypeEnum.EDZ.getCode()));
                ticket.setEdzPrice(edzPrice);
                ticket.setRw(countSeat(date, trainCode, SeatTypeEnum.RW.getCode()));
                ticket.setRwPrice(rwPrice);
                ticket.setYw(countSeat(date, trainCode, SeatTypeEnum.YW.getCode()));
                ticket.setYwPrice(ywPrice);

                ticket.setCreateTime(now);
                ticket.setUpdateTime(now);
                dailyTrainTicketMapper.insert(ticket);
            }
        }
        LOG.info("生成日期【{}】车次【{}】的余票信息结束", DateUtil.formatDate(date), trainCode);
    }

    public int countSeat(Date date, String trainCode, String seatType) {
        DailyTrainSeatExample dailyTrainSeatExample = new DailyTrainSeatExample();
        dailyTrainSeatExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode)
                .andSeatTypeEqualTo(seatType);
        long count = dailyTrainSeatMapper.countByExample(dailyTrainSeatExample);
        if (count == 0) {
            // 表示没有这种类型的座位
            return -1;
        }
        return Math.toIntExact(count);
    }

    public DailyTrainTicket selectByUnique(Date date, String trainCode, String start, String end) {
        DailyTrainTicketExample dailyTrainTicketExample = new DailyTrainTicketExample();
        dailyTrainTicketExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode)
                .andStartEqualTo(start)
                .andEndEqualTo(end);
        List<DailyTrainTicket> list = dailyTrainTicketMapper.selectByExample(dailyTrainTicketExample);
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }
}